// pages/lock_detail/lock_detail.js
const app = getApp()
var util = require('../../utils/util.js');
var request = require('../../utils/aliyun-api-gateway.js').request
Page({

  /**
   * 页面的初始数据
   */
  data: {
    windowHeight: 0,
    lockUIHeight: 0,
    topHeight: 0,
    ifBleConnected: false,
    ifWiFiConnected: false,
    ifTouch: false,
    top: 0,
    lockOpInfo: [],
    showList: [],
    showList1 : [],
    devIndex: 0,
    info: null,
    top_:470,
    top_i:470,
    refresh: 'refresh',
    refreshstate:1,   //0:可以进入刷新状态；1:在刷新中；2:不可以进入刷新状态
    height:730,
    startY:0,
    scrollToTop:true,
    netOk: true,
    currentTime:Date.now(),
    isLoading:1,      //0：点击加载更多；1：正在加载；2：全部加载完毕；3：加载失败
    ifstarted: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options.index)
    // console.log(JSON.parse(options.deviceInfo))
    var data = app.globalData.kvStorage
    var that = this
    var windowHeight = (app.globalData.SystemInfo.windowHeight * (750 / app.globalData.SystemInfo.windowWidth))
    that.setData({
      height: windowHeight-470,
      devIndex: options.index,
      info: data.deviceList[options.index]
    })
    // console.log(that.data.height)
  
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType
        if (networkType === 'none') {
          that.setData({
            ifWiFiConnected: false
          });
        } else {
          that.setData({
            ifWiFiConnected: true
          });
        }
      }
    })
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowHeight: res.windowHeight,
          lockUIHeight: res.windowHeight*0.5
        })
      }
    })
    that.parseLockOpInfo()
    setInterval(function () {
      that.parseLockOpInfo()
    }, 3000)
    that.update(Date.now(), 5, true).then(result=>{
      that.data.currentTime = result
    }
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    wx.onNetworkStatusChange(function (res) {
      if (res.isConnected) {
        that.setData({
          ifWiFiConnected: true
        });
      } else {
        that.setData({
          ifWiFiConnected: false
        });
      }
    })
    var data = app.globalData.kvStorage;
    that.setData({
      info: data.deviceList[that.data.devIndex]
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 跳转设备设置页面
   */
  openSettingsEvent: function () {
    var that = this
    util.NetStatusOk().then(function () {
      wx.navigateTo({
        url: "../settings/settings?index=" + that.data.devIndex
      })
    })
  },

  /**
   * 跳转设备用户页面
   */
  openUserEvent: function () {
    var that = this
    util.NetStatusOk().then(function () {
      wx.navigateTo({
        url: "../open_user/open_user?index=" + that.data.devIndex
      })
    })
  },

  /**
   * 跳转开门授权页面
   */
  openPerEvent: function () {
    var that = this
    util.NetStatusOk().then(function () {
      wx.navigateTo({
        url: "../open_per/open_tmppwd/open_tmppwd?deviceName=" + that.data.info.deviceName + "&deviceNick=" + that.data.info.deviceNick
      })
    })
  },

  /**
   * 跳转设备信息页面
   */
  openModeEvent: function () {
    var that = this
    util.NetStatusOk().then(function () {
      wx.navigateTo({
        url: "../open_info/open_info?index=" + that.data.devIndex
      })
    })
  },

  /**
   * 跳转钥匙管理页面
   */
  openVoiceEvent: function () {
    var that = this
    util.NetStatusOk().then(function () {
      wx.navigateTo({
        url: "../open_code/open_code?index=" + that.data.devIndex
      })
    })
  },

  scrollTopFun(e) {
    let that = this;
    var topHeight = 0
    that.setData({
      top: e.detail.scrollTop,
    })
  },

  parseLockOpInfo: function () {
    var that = this
    var tmpInfo = wx.getStorageSync('lockOpInfo')
    that.setData({
      lockOpInfo: tmpInfo
    })
    var tmpList = []
    for (let i = 0; i < tmpInfo.info.length; i++) {
      var year = '20' + util.PrefixInteger(tmpInfo.info[i].time.year, 2)
      var month = util.PrefixInteger(tmpInfo.info[i].time.month,2)
      var day = util.PrefixInteger(tmpInfo.info[i].time.day,2)
      var hour = util.PrefixInteger(tmpInfo.info[i].time.hour, 2)
      var min = util.PrefixInteger(tmpInfo.info[i].time.min, 2)
      var sec = util.PrefixInteger(tmpInfo.info[i].time.sec,2)
      var date = year + '-' + month + '-' + day
      var time = hour + ':' + min + ':' + sec
      var week = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      var weekDate = year + '/' + month + '/' + day
      var weekNum = new Date(weekDate).getDay()
      tmpList[i] = {
        date: date,
        time: time,
        week: week[weekNum],
        userNum: tmpInfo.info[i].userNum,
        opreateType: tmpInfo.info[i].opreateType,
        operateResult: tmpInfo.info[i].operateResult
      };
    }

    /*
    var listItem = []
    listItem = [msg,msg,msg]
    var show = [{
      date: '2019-01-01',
      msg: listItem
    },{
      date: '2019-01-02',
      msg: listItem
    }]
    */

    var type = ['无效', '指纹', '密码', '门卡']
    var res = ['开门失败', '开门成功']
    var tmpShowList = []
    var listItem = []
    var msgList = []
    var tmpDate = ''
    var msg = ''
    if (tmpList.length > 0) {
      tmpDate = tmpList[0].date
    }
    
    for (let i = 0; i < tmpList.length; i++) {
      if (tmpDate != tmpList[i].date) {
        tmpShowList.push(listItem)
        msgList = []
        tmpDate = tmpList[i].date
      }

      if (tmpList[i].operateResult == 0) {
        msg = tmpList[i].time + '  ' + util.PrefixInteger(tmpList[i].userNum,2) + '号用户' + '开门失败'
      }
      else {
        msg = tmpList[i].time + '  ' + util.PrefixInteger(tmpList[i].userNum,2) + '号用户使用' + type[tmpList[i].opreateType] + '开门成功'
      }
      
      msgList.push(msg)
      listItem = {
        date: tmpList[i].date + '  ' + tmpList[i].week,
        msg: msgList
      }
    }
    tmpShowList.push(listItem)
    // that.setData({
    //   showList: tmpShowList
    // })
  },
  /***************************插入通知或报警信息***************************/
  insertMsg: function (msgs, k, datetime, notiType,i,j){
    var that = this;
    if (that.data.showList1[j] == null) {  //showList1[j]为空
      k = 0;
      var MSG = [];
      MSG.push({
        time: datetime[1],
        msg: msgs,
        notiType: notiType    //0:开门；1：报警；2：故障；3：开门失败；4：事件
      })
      that.data.showList1[j] = {
        date_: datetime[0],
        date: datetime[0]+'  '+datetime[2],
        msg: MSG,
      }
      i++;
    }
    else if (datetime[0] == that.data.showList1[j].date_) {  //是同一天的消息
      var MSG = that.data.showList1[j].msg
      for (; k <= MSG.length; k++) {
        if ((MSG[k] == null) || MSG[k].time < datetime[1]) {
          MSG.splice(k, 0, {
            time: datetime[1],
            msg: msgs,
            notiType: notiType
          })
          k++;
          break;
        }
      }
      that.data.showList1[j].msg = MSG
      i++;
    }
    else if (datetime[0] > that.data.showList1[j].date_) { //不是同一天的消息 两天中间插入一天
      var MSG = []
      MSG.push({
        time: datetime[1],
        msg: msgs,
        notiType: notiType
      })
      var tmp = {
        date_:datetime[0],
        date: datetime[0]+'  '+datetime[2],
        msg: MSG,
      }
      that.data.showList1.splice(j, 0, tmp)
      i++;
    }
    else {                //不是同一天的消息 
      k = 0;
      j++;
    }

    var ctr=[i,j,k]
    return ctr;
  },
  /***************************获取开门通知***************************/
  getDoorOpenNotification:function(start,end){
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/event/timeline/get',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "eventIdentifier": "DoorOpenNotification",
        "eventType": "info",
        "start": start,
        "end": end,
        "pageSize":200,
        "ordered":false
      }
    };
    return new Promise(function (resolve, reject){
      request(params).then(result=>{
        var types=['指纹','密码','门卡','机械钥匙'];
        // console.log(result)
        if (JSON.stringify(result.data) !== "{}") {
        //将获取到的数据存入showList
        for (let i = 0, j = 0, k = 0; i < result.data.items.length;) {  //i为result当前下标，j为showList当前下标，k为showList[j].msg的当前下标
          var date = new Date(result.data.items[i].timestamp)  //时间戳转换
          var datetime = util.formatTime(date);
          var message = result.data.items[i].eventBody;
          var id = message.KeyID;             //message
          var type = types[message.LockType-1];
          var isok = (message.IS_CHECK_OK == 1)?'开门成功':'开门失败'
          if (message.IS_CHECK_OK == 1){
            var msgs = type + id + isok
            var ctr = that.insertMsg(msgs, k, datetime, 0, i, j);//插入showList1[]
            i = ctr[0],
            j = ctr[1],
            k = ctr[2]
          }
          else if (message.IS_CHECK_OK == 0){
            var msgs = type + isok
            var ctr = that.insertMsg(msgs, k, datetime, 3, i, j);//插入showList1[]
            i = ctr[0],
            j = ctr[1],
            k = ctr[2]
          }
          else
          {
            var msgs = type + id + isok
            var ctr = that.insertMsg(msgs, k, datetime, 0, i, j);//插入showList1[]
            i = ctr[0],
            j = ctr[1],
            k = ctr[2]
            }
        }
        }
        resolve()
      })
      .catch(function(res){
        console.log(res)
        reject(res)
      })
    })
  },
  /***************************获取挟持报警***************************/
  getHijackingAlarm: function (start, end){
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/event/timeline/get',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "eventIdentifier": "HijackingAlarm",
        "eventType": "alert",
        "start": start,
        "end": end,
        "pageSize": 50,
        "ordered": false
      }
    };
    return new Promise(function(resolve,reject){
      request(params).then(result =>{
        var types = ['指纹', '密码', '门卡', '机械钥匙'];
        if (JSON.stringify(result.data) !== "{}") {
          for (let i = 0, j = 0, k = 0; i < result.data.items.length;) {  //i为result当前下标，j为showList当前下标，k为showList[j].msg的当前下标
            var date = new Date(result.data.items[i].timestamp)  //时间戳转换
            var datetime = util.formatTime(date);
            var message = result.data.items[i].eventBody;
            var id = `${message.KeyID}号`;             //message
            var type = types[message.LockType - 1];
            var msgs = id + type + '被挟持';  //拼接好的message
            var ctr = that.insertMsg(msgs, k, datetime, 1, i, j);
            i = ctr[0];
            j = ctr[1];
            k = ctr[2];
          }
        }
        resolve()
      })
      .catch(function (res) {
        console.log(res)
        reject(res)
      })
    })
  },
  /***************************获取防撬报警***************************/
  getTamperAlarm: function (start, end) {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/event/timeline/get',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "eventIdentifier": "TamperAlarm",
        "eventType": "alert",
        "start": start,
        "end": end,
        "pageSize": 50,
        "ordered": false
      }
    };
    return new Promise(function (resolve, reject) {
      request(params).then(result => {
        if (JSON.stringify(result.data)!=="{}"){
          for (let i = 0, j = 0, k = 0; i < result.data.items.length;) {  //i为result当前下标，j为showList当前下标，k为showList[j].msg的当前下标
            var date = new Date(result.data.items[i].timestamp)  //时间戳转换
            var datetime = util.formatTime(date);
            var message = result.data.items[i].eventBody;
            var msgs = "门锁可能被撬动";  //拼接好的message
            var ctr = that.insertMsg(msgs, k, datetime, 1, i, j);
            i = ctr[0];
            j = ctr[1];
            k = ctr[2];
          }
        }
        resolve()
      })
      .catch(function(res){
        console.log(res)
        reject(res)
      })
    })
  },
  /***************************获取低电量报警***************************/
  getLowElectricityAlarm: function (start, end) {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/event/timeline/get',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "eventIdentifier": "LowElectricityAlarm",
        "eventType": "alert",
        "start": start,
        "end": end,
        "pageSize": 50,
        "ordered": false
      }
    };
    return new Promise(function (resolve, reject) {
      request(params).then(result => {
        if (JSON.stringify(result.data) !== "{}") {        
          for (let i = 0, j = 0, k = 0; i < result.data.items.length;) {  //i为result当前下标，j为showList当前下标，k为showList[j].msg的当前下标
            var date = new Date(result.data.items[i].timestamp)  //时间戳转换
            var datetime = util.formatTime(date);
            var message = result.data.items[i].eventBody;
            var msgs = '剩余电量:' + message.RemainPower + '%';  //拼接好的message
            var ctr = that.insertMsg(msgs, k, datetime, 1, i, j);
            i = ctr[0];
            j = ctr[1];
            k = ctr[2];
          }
        }
        resolve()
      })
      .catch(function(res){
        console.log(res)
        reject(res)
      })
    })
  },
  /***************************获取门未锁好报警***************************/
  getDoorUnlockedAlarm: function (start, end) {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/event/timeline/get',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "eventIdentifier": "DoorUnlockedAlarm",
        "eventType": "alert",
        "start": start,
        "end": end,
        "pageSize": 50,
        "ordered": false
      }
    };
    return new Promise(function (resolve, reject) {
      request(params).then(result => {
        if (JSON.stringify(result.data) !== "{}") {
          for (let i = 0, j = 0, k = 0; i < result.data.items.length;) {  //i为result当前下标，j为showList当前下标，k为showList[j].msg的当前下标
            var date = new Date(result.data.items[i].timestamp);  //时间戳转换
            var datetime = util.formatTime(date);
            var message = result.data.items[i].eventBody;
            var msgs = '门未锁好';  //拼接好的message
            var ctr = that.insertMsg(msgs, k, datetime, 1, i, j);
            i = ctr[0];
            j = ctr[1];
            k = ctr[2];
          }
        }
        resolve()
      })
      .catch(function(res){
        console.log(res)
        reject(res)
      })
    })
  },
  /***************************获取故障上报***************************/
  getError: function (start, end) {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/event/timeline/get',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "eventIdentifier": "Error",
        "eventType": "error",
        "start": start,
        "end": end,
        "pageSize": 50,
        "ordered": false
      }
    };
    return new Promise(function (resolve, reject) {
      request(params).then(result => {
        var errorType = ["zhengchang", "刷卡模块故障","指纹模块故障","按键模块故障","显示屏故障","语音模块故障"]
        if (JSON.stringify(result.data) !== "{}") {
          for (let i = 0, j = 0, k = 0; i < result.data.items.length;) {  //i为result当前下标，j为showList当前下标，k为showList[j].msg的当前下标
            var date = new Date(result.data.items[i].timestamp)  //时间戳转换
            var datetime = util.formatTime(date);
            var message = result.data.items[i].eventBody;
            if (message.ErrorCode!=0){
              var msgs = errorType[message.ErrorCode];  //拼接好的message
              var ctr = that.insertMsg(msgs, k, datetime, 2, i, j);
              i = ctr[0];
              j = ctr[1];
              k = ctr[2];
            }
            else{
              i++;
            }
          }
        }
        resolve()
      })
      .catch(function(res){
        console.log(res)
        reject(res)
      })
    })
  },
  /***************************获取添加钥匙通知***************************/
  getKeyAddedNotification: function (start, end) {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/event/timeline/get',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "eventIdentifier": "KeyAddedNotification",
        "eventType": "info",
        "start": start,
        "end": end,
        "pageSize": 50,
        "ordered": false
      }
    };
    return new Promise(function (resolve, reject) {
      request(params).then(result => {
        var types = ['指纹', '密码', '门卡'];
        var userLimit = ['普通用户', '管理员', '挟持用户'];
        if (JSON.stringify(result.data) !== "{}") {
          for (let i = 0, j = 0, k = 0; i < result.data.items.length;) {  //i为result当前下标，j为showList当前下标，k为showList[j].msg的当前下标
            var date = new Date(result.data.items[i].timestamp)  //时间戳转换
            var datetime = util.formatTime(date);
            var message = result.data.items[i].eventBody;
            var msgs = '添加'+userLimit[message.UserLimit-1] +'钥匙:' + types[message.LockType-1] + message.KeyID;  //拼接好的message
              var ctr = that.insertMsg(msgs, k, datetime, 4, i, j);
              i = ctr[0];
              j = ctr[1];
              k = ctr[2];
            
          }
        }
        resolve()
      })
      .catch(function(res){
        console.log(res)
        reject(res)
      })
    })
  },
  /***************************获取删除钥匙通知***************************/
  getKeyDeletedNotification: function (start,end) {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/event/timeline/get',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "eventIdentifier": "KeyDeletedNotification",
        "eventType": "info",
        "start": start,
        "end": end,
        "pageSize": 50,
        "ordered": false
      }
    };
    return new Promise(function (resolve, reject) {
      request(params).then(result => {
        var types = ['删除所有钥匙','指纹', '密码', '门卡'];
        if (JSON.stringify(result.data) !== "{}") {
          for (let i = 0, j = 0, k = 0; i < result.data.items.length;) {  //i为result当前下标，j为showList当前下标，k为showList[j].msg的当前下标
            var date = new Date(result.data.items[i].timestamp)  //时间戳转换
            var datetime = util.formatTime(date);
            var message = result.data.items[i].eventBody;
            if (message.LockType == 0){
              var msgs = types[message.LockType]
            }
            else if (message.KeyID == '255'){
              var msgs = '删除钥匙:' + '全部' + types[message.LockType];  //拼接好的message
            }
            else{
              var msgs = '删除钥匙:' + types[message.LockType] + message.KeyID 
            }
            var ctr = that.insertMsg(msgs, k, datetime, 4, i, j);
            i = ctr[0];
            j = ctr[1];
            k = ctr[2];

          }
        }
        resolve()
      })
      .catch(function(res){
        console.log(res)
        reject(res)
      })
    })
  },
  query:function(){
    var that = this;
    var query = wx.createSelectorQuery()
    var top;
    query.select('.body').scrollOffset();
    query.select('.body').boundingClientRect();
    return new Promise(function (resolve, reject) {
      query.exec(function (res) {
        top = res[0].scrollTop
        resolve(top)
      })
    })
  },
  // scroll:function(e){
  //   this.data.refreshing = false;
  //   // console.log("scroll:" + e.detail.scrollTop)
  //   console.log(e.detail.deltaY)
  //   // this.query().then(result=>function(){
  //   //   console.log(result)
  //   // })
  // },
  // scrolltoupper:function(){
  //   this.data.refreshing = true;
  //   console.log("scrolltoupper")
  // },
  drawStart: function (e) {
    var that = this;
    that.data.ifstarted = false
    that.query().then(result=>{
      // console.log(result)
      if (result == 0) {
        that.data.ifstarted = true
        that.data.scrollToTop = true;
        // that.data.refreshstate = 0;
        var touch = e.touches[0]
        that.data.startY = touch.clientY
      }
      else{
        that.data.scrollToTop = false;
      }
    })
  },
  drawEnd: function (e) {
    var that = this;
    if (!that.data.ifstarted) {
      return
    }
    // console.log("start", that.data.startY)
    // console.log("end",e.changedTouches[0].clientY)
    var disY = e.changedTouches[0].clientY - that.data.startY
    if (that.data.refreshstate == 0 && that.data.scrollToTop){
      if (disY >= 50) {
        that.data.refreshstate = 1;
        that.setData({
          refresh: 'refresh1',
          top_: 570,
        })
        that.data.showList=[];
        that.data.showList1=[];
        that.update(Date.now(),5,true).then(result=>{
          that.setData({
            refresh: 'refresh',
            top_: that.data.top_i,
            netOk: true,
          })
          that.data.refreshstate = 0;
          that.data.currentTime = result
        })
        .catch(function () {
          setTimeout(() => {
            that.data.refreshstate = 0;
            that.setData({
              refresh: 'refresh',
              top_: that.data.top_i,
              netOk: false
            })
          }, 1000);
        })
      } else {
        that.setData({
          top_: that.data.top_i
        })
      }
    } 
  },
  /***************************加载**************************/
  Loading:function(){
    var that = this;
    that.setData({ isLoading:1})
    that.update(that.data.currentTime, 5, false).then(result=> {
      // console.log("加载完成")
      // that.setData({
      //   isLoading: 0,
      // })
      that.data.currentTime = result
    })
    .catch(function () {
      that.setData({
        isLoading: 3,
      })
    })
  },
 /***************************更新消息**************************/
  update:function(end,duration,isrefresh){       //获取消息结束时间（到此时为止），时间跨度（以天为单位），是否在刷新（true：刷新；false：加载）
    var that =this;
    // console.log(end, duration, isrefresh)
    if (isrefresh){
      var endDate = new Date(end)
      endDate.setHours(0,0,0,0);
      end = endDate.getTime() + 1000 * 60 * 60 * 24;
    }
    var start = end - duration * 1000 * 60 * 60 * 24;
    return new Promise(function (resolve, reject){
      that.getDoorOpenNotification(start, end)
        .then(function(){
          return that.getHijackingAlarm(start, end)
        })
        .then(function () {
          return that.getTamperAlarm(start, end)
        })
        .then(function () {
          return that.getLowElectricityAlarm(start, end)
        })
        .then(function () {
          return that.getDoorUnlockedAlarm(start, end)
        })
        .then(function () {
          return that.getError(start, end)
        })
        .then(function () {
          return that.getKeyAddedNotification(start, end)
        })
        .then(function () {
          return that.getKeyDeletedNotification(start, end)
        })
        .then(function () {
          that.setData({ 
            showList: that.data.showList1,
            isLoading: 0,
            refreshstate: 0
          });
          resolve(start);
        })
        .catch(result => {
          console.log(result)
          reject()
        })
    })
  }
})